package job

import (
	"adam2/internal/domain"
	"adam2/internal/model"
	"adam2/internal/properties"
	pDomain "anubis-framework/pkg/domain"
	"anubis-framework/pkg/io"
	"github.com/robfig/cron"
	"sync"
)

// 在协程里启动定时任务
func watchCommodityFutureDateData(commodityFutureInfoArray model.CommodityFutureInfoArray, waitGroup *sync.WaitGroup) func() {
	return func() {
		io.Infoln("开始监视期货，判断是否出现了直线上涨或直线下跌行情，是否向上突破或向下跌破设置的价格")

		c := cron.New()

		// 添加定时任务
		c.AddFunc(properties.CronProperties_.Schedule, func() {
			domain.BaseJob_.CommodityFutureMinuteDataService_.WatchStraightLineIncreaseOrDecreaseInCommodityFutureMinuteData(commodityFutureInfoArray)
		})

		// 启动定时任务
		c.Start()

		// 阻塞主线程，否则主线程退出后定时任务也会停止
		select {}

		// 协程结束
		waitGroup.Done()
	}
}

// 在协程里启动定时任务
func watchStockTransactionDataAll(waitGroup *sync.WaitGroup) func() {
	return func() {
		io.Infoln("开始监视股票，判断是否出现了直线上涨或直线下跌行情，是否向上突破或向下跌破设置的价格")

		c := cron.New()

		// 添加定时任务
		var lastStockTransactionDataAllArray *model.StockTransactionDataAllArray
		c.AddFunc(properties.CronProperties_.Schedule, func() {
			var serviceResult *pDomain.ServiceResult = domain.BaseJob_.StockTransactionDataAllServiceImpl_.WatchStraightLineIncreaseOrDecreaseInStockTransactionMinuteData(lastStockTransactionDataAllArray)
			lastStockTransactionDataAllArray = serviceResult.Result.(*model.StockTransactionDataAllArray)
		})

		// 启动定时任务
		c.Start()

		// 阻塞主线程，否则主线程退出后定时任务也会停止
		select {}

		// 协程结束
		waitGroup.Done()
	}
}

// 先启动协程，每个协程再启动定时任务
func StartCron() {

	io.Infoln("先启动协程，协程中再启动定时任务，定时任务轮询每个期货")

	// 关闭协程池
	defer domain.CoroutinePool_.Pool_.Release()

	// 监控期货
	if properties.PythonProperties_.WatchCommodityFutureMinuteDataStraightLineIncreaseDecreaseEnable ||
		properties.PythonProperties_.WatchCommodityFutureMinuteDataUpOrDownPriceEnable {
		var serviceResult *pDomain.ServiceResult = domain.BaseJob_.CommodityFutureInfoService_.FindAll()
		if serviceResult.Success == true {
			var commodityFutureInfoArray model.CommodityFutureInfoArray = serviceResult.Result.(model.CommodityFutureInfoArray)
			domain.CoroutinePool_.Pool_.Submit(watchCommodityFutureDateData(commodityFutureInfoArray, &domain.CoroutinePool_.WaitGroup_))
			domain.CoroutinePool_.WaitGroup_.Add(1)
		}
	}

	// 监控股票
	if properties.PythonProperties_.WatchStockTransactionMinuteDataStraightLineIncreaseDecreaseEnable ||
		properties.PythonProperties_.WatchStockTransactionMinuteDataUpOrDownPriceEnable {
		domain.CoroutinePool_.Pool_.Submit(watchStockTransactionDataAll(&domain.CoroutinePool_.WaitGroup_))
		domain.CoroutinePool_.WaitGroup_.Add(1)
	}

	// 等待协程调用结束
	domain.CoroutinePool_.WaitGroup_.Wait()
}
